<?php
namespace app\common\model;

/**
 * 用户认证类
 *
 * Class Auth
 * @package app\common\model
 */
class Auth
{

    private $_token;

    private $_appId;

    private $_auth = [];

    /**
     * 验证方式
     *
     * @var string
     */
    private $_type = 'client';

    /**
     * Auth constructor.
     * @param array $params
     */
    public function __construct(array $params = [])
    {

        $this->_type = Config::get('type', 'auth');

        /**
         * 客户端方式验证
         */
        if ($this->_type == 'client') {
            $this->_auth = Config::get('data', 'auth');
            $params['app_id'] = $params['app_id'] ?? null;
            $params['secret'] = $params['secret'] ?? null;
            $this->loginByClient($params['app_id'], $params['secret']);
        } else {

            // 必须开启redis
            $str = Redis::instance()->get(md5($params['token']));
            $this->_token = $str ? str_replace('think_serialize:', '', $str) : null;
        }

    }

    /**
     * 客户端登录
     *
     * @param $appId
     * @param $secret
     * @return boolean
     */
    public function loginByClient($appId, $secret)
    {
        $flag = false;
        foreach ($this->_auth as $key => $value) {
            if ($appId == $value['app_id'] && $secret == $value['secret']) {
                $flag = true;
                $this->_appId = $value['app_id'];
                return $flag;
            }
        }
        return $flag;
    }

    /**
     * 验证当前
     *
     * @return boolean
     */
    public function verify()
    {
        return !empty($this->_token) || !empty($this->_appId);
    }

    /**
     * 获取当前token type=token的情况下
     *
     * @return array|mixed
     */
    public function getToken()
    {
        return $this->verify() ? unserialize($this->_token) : [];
    }

    /**
     * 获取当前appId type=client的情况下
     *
     * @return string
     */
    public function getAppId()
    {
        return $this->verify() ? $this->_appId : '';
    }

}